package com.b2c.ftysys.action;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.b2c.ftysys.constants.FtySysConstants;
import com.b2c.ftysys.domain.B2cFsyStaff;
import com.b2c.ftysys.sevice.ServicesException;
import com.b2c.ftysys.sevice.StaffInfoService;

@Controller
public class StaffAction {

	@Autowired
	private ServletContext servletContext = null;

	@Autowired
	StaffInfoService staffInfoService = null;

	@RequestMapping("staff")
	public String toStaffPage(HttpServletRequest request) {
		B2cFsyStaff example = new B2cFsyStaff();
		request.setAttribute("dataList",
				staffInfoService.queryStaffListByClause(example));
		request.setAttribute("staff", example);
		return "staff";
	}

	@RequestMapping(method=RequestMethod.POST, value="staff")
	public String queryStaff(B2cFsyStaff staff, HttpServletRequest request) {
		if (null == staff)
			staff = new B2cFsyStaff();
		request.setAttribute("dataList",
				staffInfoService.queryStaffListByClause(staff));
		request.setAttribute("staff", staff);
		return "staff";
	}

	@RequestMapping("getStaffByPinyin")
	public void getStaffByPinyin(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String pinYinName = request.getParameter("q");
		if (StringUtils.isEmpty(pinYinName))
			return;

		for (B2cFsyStaff staff : staffInfoService.queryByPinyin(pinYinName
				.toUpperCase())) {
			response.setCharacterEncoding("UTF-8");
			response.getWriter().println(
					staff.getPinyinName() + "|" + staff.getStaffName());
		}
	}

	@RequestMapping(method = RequestMethod.POST, value = "importStaff")
	public String importStaff(HttpServletRequest request,
			@RequestParam("excelFile") CommonsMultipartFile mFile) {

		if (!mFile.isEmpty()) {
			String path = servletContext.getRealPath("/")
					+ FtySysConstants.STAFF_IMPORT_EXCEL_FILE_PREFIX; // 获取本地存储路径
			String orderFileName = new Date().getTime()
					+ FtySysConstants.STAFF_IMPORT_EXCEL_FILE_SUBFIX;
			File file = new File(path + orderFileName); // 新建一个文件
			try {
				mFile.getFileItem().write(file);
				staffInfoService.ImportExcel(file.getAbsolutePath());
			} catch (ServicesException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("fileAddr", mFile.getFileItem().getName());
		}
		return "redirect:/staff.do";
	}
}
